"ui";
/**
 * 编写人:      稻草人(Mr.Yu)
 * 编写时间:    2022-09-17 15:22:17
 * 最后修改:    2022-09-21 11:14:28
 * 项目描述:
 *     简单的使用webview运行html展现UI界面并与Autojs进行交互,实现脚本逻辑.
 */
util.extend( disableSwipViewpager, $ui.Widget );
$ui.registerWidget( "disableSwipViewpager", disableSwipViewpager );

$ui.layout(
    <disableSwipViewpager id="viewpager">
        <frame>
            <webview id="web" w="*" h="*"></webview>
        </frame>
        <frame>
            <vertical>
                <appbar>
                    <toolbar id="titlebar" background="#F1F2E5" titleTextColor="#333333" title="日志" />
                </appbar>
                <globalconsole id="console" background="#F1F2E5" w="*" h="*"></globalconsole>
            </vertical>   
        </frame>
    </disableSwipViewpager>   
);
importClass( android.webkit.WebSettings );
importClass( android.view.MotionEvent );
let webSettings = $ui.web.getSettings();
webSettings.setJavaScriptEnabled( true );
webSettings.setDomStorageEnabled( true );

const jsBridge = $ui.web.jsBridge;
const webRoot = $files.join( $files.cwd(), "static" );
$ui.web.loadUrl( `file://${webRoot}/index.html` );

activity.setSupportActionBar( $ui.titlebar );
activity.getSupportActionBar().setDisplayHomeAsUpEnabled( true );

let mUtil = new MyDrawableUtil();
let mDrawable = mUtil.create( "ic_keyboard_arrow_left_black_48dp", 30 );
mDrawable.setTint( colors.parseColor( "#333333" ) );
activity.getSupportActionBar().setHomeAsUpIndicator( mDrawable );

$ui.titlebar.setNavigationOnClickListener({
    onClick: function () {
        $ui.viewpager.setCurrentItem( 0 );
    }
});
//在autojs的控制台输出webview控制台的消息
$ui.web.events.on( "console_message", ( event, msg ) => {
    console.log( msg.message() );
} );
//在webview中调用autojs的方法
jsBridge.handle( 'show-log', () => {
    // $app.startActivity( "console" );
    ui.run( () => {
        $ui.viewpager.setCurrentItem( 1 );
    } );
} )
.handle( "runScript", (event, config ) => {
    main( config );
} )
.handle( "setStatusBarColor", ( event, color ) => {
    $ui.run( () => {
        $ui.statusBarColor( color.colorHex() );
    } );
} )
.handle( "getServiceStatus", () => {
    let foreground = $settings.isEnabled( "foreground_service", enabled );
    let accessible = auto.service;
    let serviceStatus = {
        foreg : foreground,
        access : accessible
    }
    return serviceStatus;
} )
.handle( "setForegroundService", ( event, enable ) => {
    $settings.setEnabled('foreground_service', enable);
} )
.handle( "setAccessibleService", ( event, enable ) => {
    if ( enable && auto.service == null ) {
        app.startActivity({
            action: "android.settings.ACCESSIBILITY_SETTINGS"
        });
    } else if ( !enable && auto.service != null ) {
        auto.service.disableSelf();
    }
} )
.handle( "hasAccessible", () => {
    if ( auto.service != null ) {
        return true;
    }
    return false;
} )
.handle( "echoToast", ( event, msg ) => {
    toastLog( msg );
} )
.handle( "exit", () => {
    $ui.finish();
} )

$ui.emitter.on("resume", function() {
    if ( $ui.web.getUrl().toString().endsWith( "index.html" ) ) {
        $ui.web.reload();
    }
});

function main( config ) {
    //这里写自动化脚本逻辑
    console.show();
    console.log( "这里执行了autojs的自动化脚本逻辑" );
    console.log( "本次执行次数: " + config.runCounts );
    console.log( "本次执行时间: " + config.runTimes );
    console.log( "文本一: " + config.msg1 );
    console.log( "文本二: " + config.msg2 );
    console.log( "文本三: " + config.msg3 );
    console.log( "排除性别: " + config.shutOut );
    console.log( "脚本执行完毕" );
    sleep( 3000 );
    console.hide();
}

String.prototype.colorHex = function () {
    // RGB颜色值的正则
    var reg = /^(rgb|RGB)/;
    var color = this;
    if (reg.test(color)) {
        var strHex = "#";
        // 把RGB的3个数值变成数组
        var colorArr = color.replace(/(?:\(|\)|rgb|RGB)*/g, "").split(",");
        // 转成16进制
        for (var i = 0; i < colorArr.length; i++) {
        var hex = Number(colorArr[i]).toString(16);
        if (hex === "0") {
            hex += hex;
        }
        strHex += hex;
        }
        return strHex;
    } else {
        return String(color);
    }
};

//处理系统返回按钮
var isCanFinish = false;
var isCanFinishTimeout;
$ui.emitter.on( "back_pressed", e => {
    if ( $ui.web.canGoBack() ) {    //判断UI界面是否可以返回上一页
        webSettings.setCacheMode( WebSettings.LOAD_NO_CACHE );
        $ui.web.goBack();
        e.consumed = true;      //为true 确保UI界面不结束
    } else if ( $ui.viewpager.getCurrentItem() == 1 ) {     //viewpager的跳转, 从日志界面返回webview
        $ui.viewpager.setCurrentItem( 0 )
        e.consumed = true;
    } else if (!isCanFinish) {      //在主界面连续按两次返回键退出
        toast("连续按两次返回键退出");
        isCanFinish = true;
        isCanFinishTimeout=setTimeout(() => {
            isCanFinish = false;
        }, 700);
        e.consumed = true;
    } else {
        clearTimeout(isCanFinishTimeout);
        e.consumed = false;
    };
});

/**
 * 禁用viewpager左右滑动
 */
function disableSwipViewpager() {
    $ui.Widget.call(this);
    this.render = function () {
        return JavaAdapter( com.stardust.autojs.core.ui.widget.JsViewPager, {
            onInterceptTouchEvent: function () {
                return false;
            },
            onTouchEvent: function () {
                return false;
            },
        }, context );
    };
}

function MyDrawableUtil() {
    importClass(android.graphics.Bitmap);
    importClass(android.graphics.BitmapFactory);
    importClass(android.graphics.drawable.BitmapDrawable);
    const resources = context.getResources();
    /** dp2px 互转 */
    const scale = resources.getDisplayMetrics().density;
    let dp2px = dp => parseInt(Math.floor(dp * scale + 0.5));
    let px2dp = px => parseInt(Math.floor(px / scale + 0.5));

    this.create = function (name, size) {
        return zoomImage(getResID(name), dp2px(size))
    }

    function getResID(name) {
        return resources.getIdentifier(name, "drawable", context.getPackageName())
    }

    function zoomImage(resId, size) {
        let oldBmp = BitmapFactory.decodeResource(resources, resId);
        let newBmp = Bitmap.createScaledBitmap(oldBmp, size, size, true);
        let drawable = new BitmapDrawable(resources, newBmp);
        oldBmp.recycle();
        return drawable;
    }
}
